package cn.kxlove.zhbj.pager.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.viewpagerindicator.CirclePageIndicator;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

import cn.kxlove.zhbj.NewsDetailActivity;
import cn.kxlove.zhbj.R;
import cn.kxlove.zhbj.domain.respone.NewsBean;
import cn.kxlove.zhbj.domain.respone.NewsMenuBean;
import cn.kxlove.zhbj.pager.BaseMenuDetailPager;
import cn.kxlove.zhbj.common.Common;
import cn.kxlove.zhbj.utils.PrefUtils;
import cn.kxlove.zhbj.view.HorizontalScrollViewPager;
import cn.kxlove.zhbj.view.RefreshListView;

/**
 * @author kxlove 16/1/28 12:25
 */
public class TabDetailPager extends BaseMenuDetailPager implements ViewPager.OnPageChangeListener{


    @ViewInject(R.id.vp_top_news)
    private HorizontalScrollViewPager mViewPager;

    @ViewInject(R.id.lv_news)
    private RefreshListView lvNews;

    @ViewInject(R.id.tv_title)
    private TextView tvTitle;

    @ViewInject(R.id.indicator)
    private CirclePageIndicator mIndicator;

    private NewsMenuBean.NewsTabData mTabData;

    private String mUrl;// 当前页签网络数据的url

    private ArrayList<NewsBean.TopNews> mTopNewsList;// 头条新闻数据
    private ArrayList<NewsBean.News> mNewsList;// 普通新闻数据

    private NewsAdapter mNewsAdapter;

    private String mMoreUrl;// 下一页地址

    public TabDetailPager(Activity activity, NewsMenuBean.NewsTabData newsTabData) {
        super(activity);
        mTabData = newsTabData;
        mUrl = Common.SERVER_URL+newsTabData.url;
    }
    //TextView view;
    @Override
    public View initView() {

        View view = View.inflate(mActivity, R.layout.pager_tab_detail,null);
        x.view().inject(this,view);

        View headerView = View.inflate(mActivity,R.layout.list_header,null);
        x.view().inject(this,headerView);

        lvNews.addHeaderView(headerView);

        lvNews.setOnRefreshListener(new RefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDataFromServer();
            }

            @Override
            public void loadMore() {
                if (mMoreUrl != null) {
                    getMoreDataFromServer();
                } else {
                    Toast.makeText(mActivity, "没有更多数据了...", Toast.LENGTH_SHORT)
                            .show();
                    // 收起加载更多控件
                    lvNews.onRefreshComplete(true);
                }
            }


        });

        lvNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsBean.News news = mNewsList.get(position);
                // 标记已读(一旦新闻被点击,就将新闻id保存在sp中)
                // key: read_ids, values: 35311,35312,35313,
                String readIds = PrefUtils.getString(mActivity, "read_ids", "");
                // "" = "" + 3351 + "," ->3351,
                // 3351, = 3351,3352,
                if (!readIds.contains(news.id)) {// 已读ids中不包含当前id,才进行追加
                    readIds = readIds + news.id + ",";// 将已读新闻id追加到已读ids中
                    PrefUtils.putString(mActivity, "read_ids", readIds);
                }

                // 刷新listview,更新已读状态
                // mNewsAdapter.notifyDataSetChanged();

                // 局部刷新
                TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
                tvTitle.setTextColor(Color.GRAY);

                // 跳到新闻详情页
                Intent intent = new Intent();
                intent.putExtra("url", news.url);// 将url参数传递到下个activity
                intent.setClass(mActivity, NewsDetailActivity.class);
                mActivity.startActivity(intent);
            }
        });
        return view;
    }

    private void getMoreDataFromServer() {
        RequestParams params = new RequestParams(mMoreUrl);
        x.http().get(params, new Callback.CommonCallback<NewsBean>() {
            @Override
            public void onSuccess(NewsBean result) {
                processData(result,true);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                lvNews.onRefreshComplete(true);
            }
        });
    }

    @Override
    public void initData() {
        super.initData();

        getDataFromServer();
    }

    private void getDataFromServer() {
        RequestParams params = new RequestParams(mUrl);
        x.http().get(params, new Callback.CommonCallback<NewsBean>() {
            @Override
            public void onSuccess(NewsBean result) {
                processData(result,false);
                // 收回下拉刷新控件
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                lvNews.onRefreshComplete(true);
            }
        });
    }

    private void processData(NewsBean result,boolean isMore) {

        // 初始化下一页链接
        String moreUrl = result.data.more;
        if (!TextUtils.isEmpty(moreUrl)) {
            mMoreUrl = Common.SERVER_URL + moreUrl;
        } else {
            mMoreUrl = null;// 没有下一页数据了
        }

        if (!isMore) {
            mTopNewsList = result.data.topnews;

            if (!mTopNewsList.isEmpty()){
                mViewPager.setAdapter(new TopNewsAdapter());
                mIndicator.setViewPager(mViewPager);
                mIndicator.setSnap(true);// 快照方式展示
                mIndicator.setOnPageChangeListener(this);

                //初始化第一个标题
                tvTitle.setText(mTopNewsList.get(0).title);
                mIndicator.onPageSelected(0);
            }

            mNewsList = result.data.news;
            if (mNewsList != null) {
                mNewsAdapter = new NewsAdapter();
                lvNews.setAdapter(mNewsAdapter);
            }
        }else {
            ArrayList<NewsBean.News> moreNews = result.data.news;
            mNewsList.addAll(moreNews);// 将更多数据追加给现有的集合
            mNewsAdapter.notifyDataSetChanged();
        }

    }

    class NewsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mNewsList.size();
        }

        @Override
        public NewsBean.News getItem(int position) {
            return mNewsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;

            if (convertView==null){
                convertView = View.inflate(mActivity,R.layout.list_item_news,null);
                holder = new ViewHolder();
                x.view().inject(holder,convertView);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }

            NewsBean.News news = getItem(position);

            x.image().bind(holder.ivIcon,news.listimage,Common.imageOptions);

            holder.tvTitle.setText(news.title);
            holder.tvTime.setText(news.pubdate);

            // 判断已读未读
            String readIds = PrefUtils.getString(mActivity, "read_ids", "");
            if (readIds.contains(news.id)) {
                // 标题置灰
                holder.tvTitle.setTextColor(Color.GRAY);
            } else {
                // 标题置黑
                holder.tvTitle.setTextColor(Color.BLACK);
            }
            return convertView;
        }
    }

    static class ViewHolder {
        @ViewInject(R.id.iv_icon)
        public ImageView ivIcon;
        @ViewInject(R.id.tv_title)
        public TextView tvTitle;
        @ViewInject(R.id.tv_time)
        public TextView tvTime;
    }

    class TopNewsAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mTopNewsList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView view = new ImageView(mActivity);
            view.setScaleType(ImageView.ScaleType.FIT_XY);
            x.image().bind(view,mTopNewsList.get(position).topimage, ImageOptions.DEFAULT);
            container.addView(view);
            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    System.out.println("头条新闻被点击");
                    NewsBean.TopNews topNews = mTopNewsList.get(position);

                    // 跳到新闻详情页
//                    Intent intent = new Intent();
//                    intent.putExtra("url", topNews.url);// 将url参数传递到下个activity
//                    intent.setClass(mActivity, NewsDetailActivity.class);
//                    mActivity.startActivity(intent);
                }
            });

            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        NewsBean.TopNews topNews = mTopNewsList.get(position);
        tvTitle.setText(topNews.title);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
